package com.coolw.data.migrate.common.alarm;

import com.coolw.data.migrate.common.config.MailProperties;
import com.coolw.data.migrate.entity.DataMigrateLogEntity;
import com.coolw.data.migrate.enums.MigrateStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.split.SplitUtil;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.text.MessageFormat;
import java.util.List;

/**
 * 邮件告警
 *
 * @author coolw
 * @date 2024/2/21 15:49
 */
@Slf4j
@Component
public class EmailAlarm implements Alarm {

    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private MailProperties mailProperties;

    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public boolean doAlarm(DataMigrateLogEntity record) {
        String content = MessageFormat.format(getTemplate()
                , record.getId()
                , record.getSourceTableName()
                , record.getTargetTableName()
                , record.getTotalSize()
                , record.getSuccessSize()
                , record.getFailSize()
                , MigrateStatusEnum.getDesc(record.getStatus())
                , record.getCost()
                , record.getAlarmCount()
                , record.getRemark()
                , record.getReqParam());
        return send(content);
    }

    @Override
    public boolean doAlarm(List<DataMigrateLogEntity> records) {
        String content;

        // 使用thymeleaf模板
        Context context = new Context();
        context.setVariable("records", records);
        try {
            content = templateEngine.process("data_migrate_alarm", context);
        } catch (Exception e) {
            throw new RuntimeException("渲染数据迁移告警模板失败", e);
        }

        return send(content);
    }

    private boolean send(String content) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getFrom(), "coolw");
            // 收件人，多个用英文逗号隔开
            helper.setTo(SplitUtil.splitToArray(mailProperties.getTo(), ","));
            // 抄送人，多个用英文逗号隔开
            if (StrUtil.isNotBlank(mailProperties.getCc())) {
                helper.setCc(SplitUtil.splitToArray(mailProperties.getCc(), ","));
            }
            // 邮件主题
            helper.setSubject("数据迁移-失败告警");
            // 邮件内容
            helper.setText(content, true);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.warn("数据迁移-失败告警,邮件发送失败", e);
            return false;
        }
        return true;
    }

    private String getTemplate() {
        String mailBodyTemplate = "<h5>" + "数据迁移-失败告警" + "：</span>" +
                "<table border=\"1\" cellpadding=\"3\" style=\"border-collapse:collapse; width:80%;\" >\n" +
                "   <thead style=\"font-weight: bold;color: #ffffff;background-color: #ff8c00;\" >" +
                "      <tr>\n" +
                "         <td width=\"10%\" >" + "主键" + "</td>\n" +
                "         <td width=\"10%\" >" + "源表名" + "</td>\n" +
                "         <td width=\"10%\" >" + "目标表名" + "</td>\n" +
                "         <td width=\"10%\" >" + "预期迁移数量" + "</td>\n" +
                "         <td width=\"10%\" >" + "成功迁移数量" + "</td>\n" +
                "         <td width=\"10%\" >" + "失败迁移数量" + "</td>\n" +
                "         <td width=\"10%\" >" + "迁移状态" + "</td>\n" +
                "         <td width=\"10%\" >" + "耗时（毫秒）" + "</td>\n" +
                "         <td width=\"10%\" >" + "告警次数" + "</td>\n" +
                "         <td width=\"10%\" >" + "备注" + "</td>\n" +
                "         <td width=\"10%\" >" + "请求参数" + "</td>\n" +
                "      </tr>\n" +
                "   </thead>\n" +
                "   <tbody>\n" +
                "      <tr>\n" +
                "         <td>{0}</td>\n" +
                "         <td>{1}</td>\n" +
                "         <td>{2}</td>\n" +
                "         <td>{3}</td>\n" +
                "         <td>{4}</td>\n" +
                "         <td>{5}</td>\n" +
                "         <td>{6}</td>\n" +
                "         <td>{7}</td>\n" +
                "         <td>{8}</td>\n" +
                "         <td>{9}</td>\n" +
                "         <td>{10}</td>\n" +
                "      </tr>\n" +
                "   </tbody>\n" +
                "</table>";

        return mailBodyTemplate;
    }
}
